﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;

namespace GenericLibrary.Xml.Xsl {

    public static class XslTransformCompiler {

        public static CompilerErrorCollection Compile( XmlReader reader, string assemblyDir, string typeName, XsltSettings settings, XmlResolver resolver ) {
            try {

                Directory.CreateDirectory( assemblyDir );
                AssemblyName an = new AssemblyName( typeName );
                AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly( an, AssemblyBuilderAccess.Save, assemblyDir );
                ModuleBuilder mb = ab.DefineDynamicModule( typeName, typeName + ".dll", true );
                TypeBuilder tb = mb.DefineType( typeName, TypeAttributes.Public | TypeAttributes.Class );
                CompilerErrorCollection errors = XslCompiledTransform.CompileToType( reader, settings, resolver, true, tb, string.Format( @"{0}\{1}.script1.dll", assemblyDir, typeName ) );
                ab.Save( typeName + ".dll" );
                return errors;
            } catch( Exception ) {
                Debug.Assert( false );
                throw;
            } finally {
                reader.Close();
            }
        }
    }

    
}
